package com.example.coupon.service.impl;

import com.example.coupon.dao.CouponTemplateDao;
import com.example.coupon.entity.CouponTemplate;
import com.example.coupon.exception.CouponException;
import com.example.coupon.service.ITemplateBaseService;
import com.example.coupon.vo.CouponTemplateSDK;
import com.sun.org.apache.xalan.internal.xsltc.compiler.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 优惠券模版基础服务实现
 *
 * @author wangbo
 * @description:
 * @date 2021/2/1814:26
 */
@Slf4j
@Service
public class TemplateBaseServiceImpl implements ITemplateBaseService {

    @Resource
    private CouponTemplateDao couponTemplateDao;

    /**
     * 根据优惠券模版ID获取优惠券模版信息
     *
     * @param id 模版id
     * @return {@link CouponTemplate} 优惠券模版实体
     * @throws CouponException
     */
    @Override
    public CouponTemplate buildTemplateInfo(Integer id) throws CouponException {
        Optional<CouponTemplate> template = couponTemplateDao.findById(id);
        if (!template.isPresent()) {
            throw new CouponException("Template Is Not Exist: " + id);
        }
        return template.get();
    }

    /**
     * 查询所有可用的优惠券模版
     *
     * @return
     */
    @Override
    public List<CouponTemplateSDK> findAllUsableTemplate() {

        List<CouponTemplate> templates = couponTemplateDao.findAllByAvailableAndExpired(true, false);
        return templates.stream().map(this::template2TemplateSDK).collect(Collectors.toList());
    }

    /**
     * 获取模版ids到CouponTemplateSDK的映射
     *
     * @param ids 模版ids
     * @return Map<Key:模版id, value: CouponTemplateSDK>
     */
    @Override
    public Map<Integer, CouponTemplateSDK> findIds2Template(Collection<Integer> ids) {
        List<CouponTemplate> templates = couponTemplateDao.findAllById(ids);
        return templates.stream().map(this::template2TemplateSDK).collect(Collectors.toMap(
                CouponTemplateSDK::getId, Function.identity()
        ));
    }

    /**
     * 将CouponTemplate转换为CouponTemplateSDK
     *
     * @param template
     * @return
     */
    private CouponTemplateSDK template2TemplateSDK(CouponTemplate template) {
        return new CouponTemplateSDK(
                template.getId(),
                template.getName(),
                template.getLogo(),
                template.getDesc(),
                template.getCategory().getCode(),
                template.getProductLine().getCode(),
                template.getKey(),
                template.getTarget().getCode(),
                template.getRule()
        );
    }
}
